"use client";
import UserProvider from "@/components/UserProvider";
import {
  DownOutlined,
  HomeOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
} from "@ant-design/icons";

import { AntdRegistry } from "@ant-design/nextjs-registry";
import {
  Button,
  ConfigProvider,
  Dropdown,
  Layout,
  Menu,
  Popover,
  Space,
  Tag,
  Watermark,
} from "antd";
import type { Metadata } from "next";
import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";

import { MenusItem, geneRateMenuTree, getAllPath } from "@/components/utilUi";
import { IUser, useUserStore } from "@/store/userStore";
import { setCookie } from "@/lib/utils";
import admin_config from "@/config/admin_config";
import Link from "next/link";
import SwitchRole from "@/components/SwitchRole";
import zhCN from "antd/locale/zh_CN";
import "dayjs/locale/zh-cn";
import dayjs from "dayjs";
// import NotFound from "./[...not-found]/page";
import { useRouter, usePathname } from "next/navigation";
import { userLogout } from "../actions/user_action";
import '@ant-design/v5-patch-for-react-19';
import NotFound from "./[...not-found]/page";
import updateLocale from 'dayjs/plugin/updateLocale';
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
dayjs.extend(updateLocale);
dayjs.locale("zh-cn");
dayjs.updateLocale('zh-cn', {
  weekStart: 0,
});
const queryClient = new QueryClient()

const { Header, Sider, Content } = Layout;

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const [collapsed, setCollapsed] = useState(false);
  // const [openK, setOpenK] = useState<string[]>([]);
  const navList = useRef<MenusItem[]>([]);
  const [userInfo] = useUserStore((state) => [state.user]);
  const pathName = usePathname();
  const router = useRouter();
  const openK: string[] = [];

  useEffect(() => {
    window.addEventListener("wheel", (event) => {

    }, { passive: true }); // 告诉浏览器，不会调用 event.preventDefault()

  }, []);

  const calcuMenu = (menu: any) => {
    if (menu && menu.length > 0 && userInfo?.name !== 'admin') { // 只有admin用户才可以查看菜单管理
      const idx = menu.findIndex((it: any) => it.name === '菜单管理')
      if (idx > -1) {
        menu.splice(idx, 1)
      }
    }
    navList.current = geneRateMenuTree(menu);
    navList.current.forEach((it) => {
      if (pathName.startsWith(it!.key as string)) {
        openK.push(it?.key as string);
      }
    });
    return [
      {
        key: "/admin",
        label: <Link href={"/admin"}>首页</Link>,
        icon: <HomeOutlined />,
        path: "/admin",
      },
      ...navList.current,
    ];
  };
  const getMenusList = useMemo(() => {
    return calcuMenu(userInfo?.menus || []);
  }, [userInfo?.menus]);
  const permissionMenus = useMemo(() => {
    if (userInfo?.id) {
      return getAllPath(userInfo?.menus || [])
    }
    return []
  }, [userInfo?.menus, userInfo?.id]);
  const arrowMenus = [
    {
      key: "logout",
      label: (
        <Button
          type="text"
          onClick={async () => {
            await userLogout()
            window.location.href = "/login";
          }}
        >
          退出
        </Button>
      ),
    },
    {
      key: "switchRole",
      label: <SwitchRole></SwitchRole>,
    },
  ];
  const locale = zhCN;
  let is404 = false;
  if (pathName !== "/admin" && userInfo?.id) {
    if (!permissionMenus.includes(pathName)) {
      // router.replace('/admin')
      is404 = true;
      // return <NotFound></NotFound>
    }
  }

  // console.log(permissionMenus);
  return (
    <QueryClientProvider client={queryClient}>
      <UserProvider>
        <ConfigProvider locale={locale}>
          <AntdRegistry>
            <Watermark content={[userInfo?.name || '', userInfo?.roleName || '']} font={{ color: 'rgba(0, 0, 0, .08)' }}>
              <Layout style={{ height: "100vh" }}>
                <Sider trigger={null} collapsible collapsed={collapsed}>
                  <div className="demo-logo-vertical" />
                  <Menu
                    theme="dark"
                    mode="inline"
                    items={getMenusList}
                    defaultOpenKeys={openK}
                    defaultSelectedKeys={[pathName]}
                  />
                </Sider>
                <Layout>
                  <Header
                    style={{ padding: 0, background: "#fff" }}
                    className="flex justify-between"
                  >
                    <Button
                      type="text"
                      icon={
                        collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />
                      }
                      onClick={() => setCollapsed(!collapsed)}
                      style={{
                        fontSize: "16px",
                        width: 64,
                        height: 64,
                      }}
                    />
                    <div className="px-5 cursor-pointer">
                      <Dropdown menu={{ items: arrowMenus }}>
                        <Space>
                          {userInfo?.name}
                          <Tag color="orange">{userInfo?.roleName}</Tag>
                          <DownOutlined />
                        </Space>
                      </Dropdown>
                    </div>
                  </Header>
                  <Content
                    style={{
                      margin: "16px",
                      boxShadow: "0 0 10px rgba(0,0,0,0.2)",
                      borderRadius: "10px",
                    }}
                  >
                    {
                      is404 ? <NotFound></NotFound> : children
                    }
                  </Content>
                </Layout>
              </Layout>
            </Watermark>

          </AntdRegistry>
        </ConfigProvider>
      </UserProvider>
    </QueryClientProvider>
  );
}
